﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Century.EnterpriseLibrary.Globalization.DbProvider;
using log4net;


namespace Century.EnterpriseLibrary.Globalization
{
    public class SiteConfigReader
    {
        #region [ Private Member(s) ]

        public ILog Log
        {
            get
            {
                return Century.EnterpriseLibrary.LogHandler.Loging.LogWithName("SiteConfigReader");
            }
        }

        #endregion

        #region [ Singleton ]

        public static readonly SiteConfigReader Instance = new SiteConfigReader();
        private SiteConfigReader()
        {
            FillCofnigList();
        }

        private void FillCofnigList()
        {
            using (DbGlobalizationContext db = new DbGlobalizationContext())
            {
                try
                {
                  siteConfigList =  db.CountrySiteConfigs.ToList();
                }
                catch (Exception exc)
                {
                    Log.Error("Error on load Site Config List", exc);
                }

            }
        }

        #endregion

        #region [ Private Method(s) ]

        private List<CountrySiteConfig> siteConfigList = new List<CountrySiteConfig>();

        #endregion

        #region [ Public Method(s) ]

        public string GetConfig(SiteConfigKey confKey)
        {
            
            if (siteConfigList.Any(c => c.CountrySiteId == PersistData.CurrentSiteId && c.ConfigKey == confKey.ToString()))
            {
                return siteConfigList.First(c => c.CountrySiteId == PersistData.CurrentSiteId && c.ConfigKey == confKey.ToString()).ConfigValue;
            }
            else
            {
                string value = string.Empty;
                string valueType = "string";
                if (siteConfigList.Any(c => c.ConfigKey == confKey.ToString() && c.CountrySiteId == 14))
                {
                    CountrySiteConfig temp = siteConfigList.First(c => c.ConfigKey == confKey.ToString() && c.CountrySiteId == 14);
                    value = temp.ConfigValue;
                    valueType = temp.ValueType;
                }
                CountrySiteConfig countrySiteConfig = new CountrySiteConfig { ConfigKey = confKey.ToString(), ConfigValue = value, CountrySiteId = PersistData.CurrentSiteId, ValueType = valueType };

                using (DbGlobalizationContext db = new DbGlobalizationContext())
                {
                    try
                    {
                        db.CountrySiteConfigs.Add(countrySiteConfig);
                        db.SaveChanges();
                        Log.FatalFormat("The Contry site config : {0}, for country site : {1} was not exist and program insert default value for this request!", confKey.ToString(), PersistData.CurrentSiteId);

                    }
                    catch (Exception exc)
                    {
                        Log.Error("Error on saving default value for Country Site Config", exc);
                    }

                }

                siteConfigList.Add(countrySiteConfig);
                return countrySiteConfig.ConfigValue;
            }
        }

        /// <summary>
        /// Saves social links
        /// </summary>
        /// <param name="values"></param>
        public  void SaveSocialNetworkLink(Dictionary<string, string> values)
        {
            string value = string.Empty;
            using (DbGlobalizationContext db = new DbGlobalizationContext())
            {
                foreach (KeyValuePair<string, string> item in values)
                {
                    value = item.Value.Trim();

                    #region update on db

                    CountrySiteConfig config = db.CountrySiteConfigs.FirstOrDefault(c => c.ConfigKey == item.Key && c.CountrySiteId == PersistData.CurrentSiteId);

                    // first get and create...
                    if (config == null)
                    {
                        GetConfig((SiteConfigKey)Enum.Parse(typeof(SiteConfigKey), item.Key));
                        config = siteConfigList.FirstOrDefault(c => c.ConfigKey == item.Key && c.CountrySiteId == PersistData.CurrentSiteId);
                    }

                    // assign new value
                    config.ConfigValue = value;

                    // commit settings
                    try
                    {
                        //db.CountrySiteConfigs.update(config);
                        db.SaveChanges();
                        Log.FatalFormat("The Contry site config : {0}, for country site : {1} was not exist and program insert default value for this request!", config.ConfigKey.ToString(), PersistData.CurrentSiteId);
                    }
                    catch (Exception exc)
                    {
                        Log.Error("Error on saving default value for Country Site Config", exc);
                    }

                    #endregion
                }
            }
        }

        public void SaveConfig(SiteConfigKey key, string value)
        {
            using (DbGlobalizationContext db = new DbGlobalizationContext())
            {
                string keyStr = key.ToString();
                CountrySiteConfig config = db.CountrySiteConfigs.FirstOrDefault(c => c.ConfigKey == keyStr && c.CountrySiteId == PersistData.CurrentSiteId);
                config.ConfigValue = value;

                // commit settings
                try
                {
                    //db.CountrySiteConfigs.update(config);
                    db.SaveChanges();
                    Log.FatalFormat("The Contry site config : {0}, for country site : {1} was not exist and program insert default value for this request!", config.ConfigKey.ToString(), PersistData.CurrentSiteId);
                }
                catch (Exception exc)
                {
                    Log.Error("Error on saving default value for Country Site Config", exc);
                }
            }
        }

        public void Reload()
        {
            FillCofnigList();
        }

        #endregion
    }


}
